import { deleteMessage, qryMessageListPage } from '@/services/message';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef } from 'react';

interface MessageItem {
  messageId: string;
  title: string;
  email: string;
  messageContent: string;
  createDate: string;
}

const MessagePage: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const handleDelete = async (messageId: string) => {
    try {
      await deleteMessage({ messageId });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns: ProColumns<MessageItem>[] = [
    {
      title: '留言编号',
      dataIndex: 'messageId',
      key: 'messageId',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      hideInSearch: true,
      width: 200,
    },
    {
      title: '留言内容',
      dataIndex: 'messageContent',
      key: 'messageContent',
      hideInSearch: true,
      ellipsis: true,
      width: 300,
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      hideInSearch: true,
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          key="delete"
          title="确定要删除这条留言吗?"
          onConfirm={() => handleDelete(record.messageId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<MessageItem>
        actionRef={actionRef}
        rowKey="messageId"
        columns={columns}
        request={async (params) => {
          const { current, pageSize, ...rest } = params;
          console.log(rest);
          const result = await qryMessageListPage({
            pageIndex: current,
            pageSize,
            param: {
              title: rest.title,
            },
          });
          return {
            data: result.list,
            total: result.total,
            success: true,
          };
        }}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
      />
    </PageContainer>
  );
};

export default MessagePage;
